package com.lanyan.web.controller.api;

import cn.hutool.core.lang.Snowflake;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.lanyan.common.annotation.RepeatSubmit;

import java.math.BigDecimal;

import com.lanyan.common.exception.ServiceException;
import com.lanyan.common.utils.SecurityUtils;
import com.lanyan.common.utils.bean.BeanUtils;
import com.lanyan.system.domain.*;
import com.lanyan.system.domain.vo.*;
import com.lanyan.system.service.*;
import io.swagger.annotations.Api;

import java.util.*;
import java.util.stream.Collectors;

import com.lanyan.common.core.domain.R;
import com.lanyan.common.core.domain.PageR;

import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lanyan.common.annotation.Log;
import io.swagger.annotations.ApiOperation;
import com.lanyan.common.core.controller.BaseController;
import com.lanyan.common.core.domain.AjaxResult;
import com.lanyan.common.core.domain.R;
import com.lanyan.common.enums.BusinessType;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import springfox.documentation.annotations.ApiIgnore;
import com.lanyan.common.utils.StringUtils;
import com.lanyan.common.utils.poi.ExcelUtil;
import com.lanyan.common.core.page.TableDataInfo;

/**
 * 订单Controller
 *
 * @author lanyan
 * @date 2024-11-26
 */
@RestController
@Api(tags = {"订单"})
@RequestMapping("/api/orders")
public class ApiOrdersController extends BaseController {
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private IAccountAddressService accountAddressService;
    @Autowired
    private IProductService productService;
    @Autowired
    private ISkuService skuService;
    @Autowired
    private IOrdersItemService ordersItemService;
    @Autowired
    private IShoppingService shoppingService;
    @Autowired
    private IAccountCouponService accountCouponService;
    @Autowired
    private IBuildingService buildingService;
    @Autowired
    private IEstateService estateService;
    @Autowired
    private ICourierService courierService;
    @Autowired
    private IEvaluateService evaluateService;
    @Autowired
    private IClassifyService classifyService;
    @Autowired
    private Snowflake snowflake;

    /**
     * 查询订单列表
     */
    @GetMapping("/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "订单类型（0商城订单 1取送订单）", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "secondType", value = "取送类型（0帮取 1帮送）", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "state", value = "订单状态（0待付款 1待接单 2进行中 3已完成 4已取消）", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "pageNum", value = "第几页", dataType = "int", dataTypeClass = int.class),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", dataTypeClass = int.class),
    })
    @ApiOperation("查询订单列表")
    public PageR<OrdersVo<OrdersItemVo>> list(@ApiIgnore Orders<OrdersItemVo> orders) {
        startPage();
        orders.setAccountId(SecurityUtils.getUserId());
        List<Orders> ordersList = ordersService.selectOrdersList(orders);
        List<OrdersVo<OrdersItemVo>> list = new ArrayList<>();
        for (Orders item : ordersList) {
            OrdersVo<OrdersItemVo> ordersVo = new OrdersVo<>();
            BeanUtils.copyBeanProp(ordersVo,item);
            ordersVo.setIsOverEvaluate("1");
            List<OrdersItem> ordersItemList = ordersItemService.lambdaQuery()
                    .eq(OrdersItem::getDelFlag, "0")
                    .eq(OrdersItem::getOrdersId, item.getOrdersId())
                    .list();
            List<OrdersItemVo> itemVoList = ordersItemList.stream().map(x -> {
                OrdersItemVo ordersItemVo = new OrdersItem();
                BeanUtils.copyBeanProp(ordersItemVo, x);
                Evaluate proEvaluate = evaluateService.lambdaQuery()
                        .eq(EvaluateVo::getDelFlag, "0")
                        .eq(EvaluateVo::getOrdersId, x.getOrdersId())
                        .eq(EvaluateVo::getProductId,x.getProductId())
                        .one();
                if (proEvaluate == null){
                    ordersItemVo.setIsEvaluate("0");
                    ordersVo.setIsOverEvaluate("0");
                }else {
                    ordersItemVo.setIsEvaluate("1");
                }
                return ordersItemVo;
            }).collect(Collectors.toList());
            ordersVo.setOrdersItemVoList(itemVoList);
            ordersVo.setCourier(courierService.getById(item.getCourierId()));
            Evaluate evaluate = evaluateService.lambdaQuery()
                    .eq(EvaluateVo::getDelFlag, "0")
                    .eq(EvaluateVo::getOrdersId, item.getOrdersId())
                    .eq(EvaluateVo::getCourierId,item.getCourierId())
                    .one();
            if (evaluate == null){
                ordersVo.setIsEvaluate("0");
                ordersVo.setIsOverEvaluate("0");
            }else {
                ordersVo.setIsEvaluate("1");
            }
            if (StringUtils.isNotEmpty(item.getFetchBuilding())){
                Building building = buildingService.getById(item.getFetchBuilding());
                Estate estate = estateService.getById(building.getEstateId());
                ordersVo.setFetchEstate(estate.getName() + building.getName());
            }
            if (StringUtils.isNotEmpty(item.getSendBuilding())){
                Building building = buildingService.getById(item.getSendBuilding());
                Estate estate = estateService.getById(building.getEstateId());
                ordersVo.setSendEstate(estate.getName() + building.getName());
            }
            list.add(ordersVo);
        }
        return PageR.page(list);
    }

    /**
     * 获取订单详细信息
     */
    @GetMapping(value = "/info")
    @ApiOperation("获取订单详细信息")
    public R<Orders<OrdersItem>> getInfo(Long ordersId) {
        Orders orders = ordersService.getById(ordersId);
        orders.setIsOverEvaluate("1");
        List<OrdersItem> ordersItemList = ordersItemService.lambdaQuery()
                .eq(OrdersItem::getDelFlag, "0")
                .eq(OrdersItem::getOrdersId, orders.getOrdersId())
                .list();
        for (OrdersItem item : ordersItemList) {
            Evaluate proEvaluate = evaluateService.lambdaQuery()
                    .eq(EvaluateVo::getDelFlag, "0")
                    .eq(EvaluateVo::getOrdersId, item.getOrdersId())
                    .eq(EvaluateVo::getProductId,item.getProductId())
                    .one();
            if (proEvaluate == null){
                item.setIsEvaluate("0");
                orders.setIsOverEvaluate("0");
            }else {
                item.setIsEvaluate("1");
            }
        }
        orders.setOrdersItemVoList(ordersItemList);
        if (StringUtils.isNotEmpty(orders.getFetchBuilding())){
            Building building = buildingService.getById(orders.getFetchBuilding());
            Estate estate = estateService.getById(building.getEstateId());
            orders.setFetchEstate(estate.getName() + building.getName());
        }
        if (StringUtils.isNotEmpty(orders.getSendBuilding())){
            Building building = buildingService.getById(orders.getSendBuilding());
            Estate estate = estateService.getById(building.getEstateId());
            orders.setSendEstate(estate.getName() + building.getName());
        }
        orders.setCourier(courierService.getById(orders.getCourierId()));
        Evaluate evaluate = evaluateService.lambdaQuery()
                .eq(EvaluateVo::getDelFlag, "0")
                .eq(EvaluateVo::getOrdersId, orders.getOrdersId())
                .eq(EvaluateVo::getCourierId,orders.getCourierId())
                .one();
        if (evaluate == null){
            orders.setIsEvaluate("0");
            orders.setIsOverEvaluate("0");
        }else {
            orders.setIsEvaluate("1");
        }
        return R.ok(orders);
    }

    /**
     * 新增订单
     */
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("save")
    @RepeatSubmit
    @ApiOperation("新增订单")
    public R<String> add(@RequestBody CreateOrdersDto createOrdersDto) throws Exception {
        Orders orders = new Orders();
        BeanUtils.copyBeanProp(orders, createOrdersDto);
        Long accountId = SecurityUtils.getUserId();
        orders.setAccountId(accountId);
        boolean team = Boolean.TRUE;
        if (createOrdersDto.getStartAddressId() != null) {
            AccountAddress accountAddress = accountAddressService.getById(createOrdersDto.getStartAddressId());
            orders.setFetchName(accountAddress.getName());
            orders.setFetchPhone(accountAddress.getPhone());
            orders.setFetchBuilding(accountAddress.getBuildingId().toString());
            orders.setFetchDetails(accountAddress.getDetails());
            if (StringUtils.equals(createOrdersDto.getType(),"1") && StringUtils.equals(createOrdersDto.getSecondType(),"0")){
                Building building = buildingService.getById(accountAddress.getBuildingId());
                Courier courier = courierService.getById(building.getCourierId());
                if (courier != null && StringUtils.equals(courier.getState(),"0")){
                    team = Boolean.FALSE;
                }
            }
        }
        if (createOrdersDto.getTakeAddressId() != null) {
            AccountAddress accountAddress = accountAddressService.getById(createOrdersDto.getTakeAddressId());
            orders.setSendName(accountAddress.getName());
            orders.setSendPhone(accountAddress.getPhone());
            orders.setSendBuilding(accountAddress.getBuildingId().toString());
            orders.setSendDetails(accountAddress.getDetails());
            if (StringUtils.equals(createOrdersDto.getType(),"0") || StringUtils.equals(createOrdersDto.getSecondType(),"1")){
                Building building = buildingService.getById(accountAddress.getBuildingId());
                Courier courier = courierService.getById(building.getCourierId());
                if (courier != null && StringUtils.equals(courier.getState(),"0")){
                    team = Boolean.FALSE;
                }
            }
        }
        String totalNo = "A" + snowflake.nextIdStr();
        orders.setTotalNo(totalNo);
        orders.setOrdersNo(snowflake.nextIdStr());
        if (StringUtils.equals(createOrdersDto.getType(), "0")) {
//            orders.setCourierId(getCourier(Long.valueOf(orders.getSendBuilding())));
        } else {
            Account account = accountService.getById(accountId);
            if (account.getVipEnd() == null || account.getVipEnd().before(new Date())){
                return R.fail(403,"请先购买会员");
//                createOrdersDto.setNeedPay("1");
//                orders.setMoney(new BigDecimal("3"));
            }
//            orders.setCourierId(getCourier(Long.valueOf(orders.getFetchBuilding())));
        }
        //发送取货码
        if (StringUtils.equals(orders.getType(),"1")){
            orders.setCode(StringUtils.generateRandomString(6));
            sendCode(orders.getSendPhone(),orders.getCode());
        }
        if (StringUtils.equals(createOrdersDto.getNeedPay(),"1")){
            orders.setState("0");
        }else {
            orders.setState("1");
        }
        ordersService.insertOrders(orders);
        if (createOrdersDto.getAccountCouponId() != null) {
            accountCouponService.lambdaUpdate()
                    .eq(AccountCouponVo::getAccountCouponId, createOrdersDto.getAccountCouponId())
                    .set(AccountCouponVo::getState, "1")
                    .set(AccountCouponVo::getUpdateTime,new Date())
                    .update();
        }
        if (StringUtils.equals(createOrdersDto.getType(), "0")) {
            List<OrdersItem> ordersItemList = new ArrayList<>();
            if (createOrdersDto.getSkuId() != null) {
                //直接购买
                OrdersItem ordersItem = new OrdersItem();
                ordersItem.setOrdersId(orders.getOrdersId());
                ordersItem.setNum(createOrdersDto.getNum());
                beauty(ordersItem,createOrdersDto.getSkuId());
                ordersItemList.add(ordersItem);
            } else {
                //购物车购买
                List<Long> shoppingIds = createOrdersDto.getShoppingIds();
                for (Long shoppingId : shoppingIds) {
                    Shopping shopping = shoppingService.getById(shoppingId);
                    OrdersItem ordersItem = new OrdersItem();
                    ordersItem.setOrdersId(orders.getOrdersId());
                    ordersItem.setNum(shopping.getNum());
                    beauty(ordersItem,shopping.getSkuId());
                    ordersItemList.add(ordersItem);
                }
                shoppingService.removeByIds(shoppingIds);
            }
            Map<String, List<OrdersItem>> map = ordersItemList.stream().collect(Collectors.groupingBy(OrdersItem::getType));
            if (map.size() > 1){
                //拆单
                Orders other = new Orders();
                BeanUtils.copyBeanProp(other,orders);
                other.setOrdersId(null);
                other.setOrdersNo(snowflake.nextIdStr());
                List<OrdersItem> liKe = map.get("0");
                List<OrdersItem> zeRi = map.get("1");
                //立即配送单金额
                BigDecimal liKeSum = liKe.stream().map(x -> {return x.getPrice().multiply(BigDecimal.valueOf(x.getNum()));}).reduce(BigDecimal.ZERO,BigDecimal::add);
                //立即配送金额占总金额比例
                BigDecimal ratio = liKeSum.divide(orders.getOriginMoney(), 2, BigDecimal.ROUND_HALF_UP);
                //立即配送单实际支付金额
                BigDecimal firstMoney = orders.getMoney().multiply(ratio).divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
                ordersService.lambdaUpdate()
                        .eq(OrdersVo::getOrdersId,orders.getOrdersId())
                        .set(Orders::getOriginMoney,liKeSum)
                        .set(OrdersVo::getMoney,firstMoney)
                        .update();
                other.setDay(createOrdersDto.getOtherDay());
                other.setReceivingTime(createOrdersDto.getOtherReceivingTime());
                other.setReceivingEndTime(createOrdersDto.getOtherReceivingEndTime());
                other.setDay(createOrdersDto.getOtherDay());
                other.setOriginMoney(createOrdersDto.getOriginMoney().subtract(liKeSum));
                other.setMoney(createOrdersDto.getMoney().subtract(firstMoney));
                ordersService.save(other);
                zeRi.stream().forEach(x -> x.setOrdersId(other.getOrdersId()));
                ordersItemService.saveBatch(liKe);
                ordersService.lambdaUpdate()
                        .eq(OrdersVo::getOrdersId, orders.getOrdersId())
                        .set(OrdersVo::getSecondType,"0")
                        .update();
                ordersItemService.saveBatch(zeRi);
                ordersService.lambdaUpdate()
                        .eq(OrdersVo::getOrdersId, other.getOrdersId())
                        .set(OrdersVo::getSecondType,"1")
                        .update();
            }else {
                ordersItemService.saveBatch(ordersItemList);
                OrdersItem item = ordersItemList.get(0);
                LambdaUpdateChainWrapper<Orders> wrapper = ordersService.lambdaUpdate()
                        .eq(OrdersVo::getOrdersId, orders.getOrdersId());
                if (StringUtils.equals(item.getType(),"0")){
                    wrapper.set(OrdersVo::getDay,createOrdersDto.getDay())
                            .set(OrdersVo::getReceivingTime,createOrdersDto.getReceivingTime())
                            .set(OrdersVo::getReceivingEndTime,createOrdersDto.getReceivingEndTime());
                }else {
                    wrapper.set(OrdersVo::getReceivingTime,createOrdersDto.getOtherReceivingTime())
                            .set(OrdersVo::getReceivingEndTime,createOrdersDto.getOtherReceivingEndTime())
                            .set(OrdersVo::getDay,createOrdersDto.getOtherDay());
                }
                wrapper.set(OrdersVo::getSecondType,item.getType())
                        .update();
            }
            for (OrdersItem ordersItem : ordersItemList) {
                Sku sku = skuService.getById(ordersItem.getSkuId());
                Product product = productService.getById(ordersItem.getProductId());
                productService.lambdaUpdate()
                        .eq(ProductVo::getProductId,product.getProductId())
                        .set(ProductVo::getStock,product.getStock()-ordersItem.getNum())
                        .update();
                skuService.lambdaUpdate()
                        .eq(SkuVo::getSkuId,sku.getSkuId())
                        .set(SkuVo::getStock,sku.getStock()-ordersItem.getNum())
                        .update();
            }
        }

        if (StringUtils.equals(createOrdersDto.getNeedPay(),"0")){
            ordersService.sendWx(orders.getOrdersId());
        }
        return R.ok(orders.getTotalNo(),team ? "" : "");
    }

    public void beauty(OrdersItem ordersItem,long skuId) throws Exception {
        Sku sku = skuService.getById(skuId);
        Product product = productService.getById(sku.getProductId());
        Classify classify = classifyService.getById(product.getTopClassifyId());
        ordersItem.setType(classify.getIsTimely());
        ordersItem.setProductId(sku.getProductId());
        ordersItem.setSkuId(skuId);
        ordersItem.setName(product.getName());
        ordersItem.setSkuName(sku.getFullName());
        ordersItem.setPrice(sku.getPrice());
        ordersItem.setIsEvaluate("0");
        ordersItem.setMainImg(product.getMainImg());
        if (sku.getStock() < ordersItem.getNum()){
            throw new Exception("库存不足");
        }
    }

    public Long getCourier(Long buildingId){
        Building building = buildingService.getById(buildingId);
        return building.getCourierId();
    }

    /**
     * 修改订单
     */
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("update")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ordersId", value = "所属订单", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "state", value = "订单状态（0待付款 1待接单 2进行中 3已完成 4已取消）", dataType = "String", dataTypeClass = String.class),
    })
    @RepeatSubmit
    @ApiOperation("修改订单")
    public AjaxResult edit(@ApiIgnore @RequestBody Orders orders) {
        StringUtils.updateRequired(orders);
        ordersService.updateOrders(orders);
        return success("修改成功");
    }

    /**
     * 删除订单
     */
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @GetMapping("/del")
    @ApiOperation("删除订单")
    public AjaxResult remove(Long ordersId) {
        ordersService.deleteOrdersByOrdersId(ordersId);
        return success("删除成功");
    }

    /**
     * 估价
     */
    @PostMapping("/assess")
    @ApiOperation("估价")
    public AjaxResult assess(@RequestBody CreateOrdersDto createOrdersDto) {
        Map<String,Object> res = new HashMap<>();
        BigDecimal all = BigDecimal.ZERO;
        String needPay = "0";
        List<Product> now = new ArrayList<>();
        List<Product> choose = new ArrayList<>();
        if (createOrdersDto.getSkuId() != null){
            Sku sku = skuService.getById(createOrdersDto.getSkuId());
            Product product = productService.getById(sku.getProductId());
            if (StringUtils.equals(product.getNeedPay(),"1")){
                needPay = "1";
            }
            if (sku.getStock() < createOrdersDto.getNum()){
                throw new ServiceException(product.getName() + "库存不足");
            }
            all = sku.getPrice().multiply(BigDecimal.valueOf(createOrdersDto.getNum()));
            product.setSkus(new ArrayList(){{add(sku);}});
            Classify classify = classifyService.getById(product.getClassifyId());
            if (StringUtils.equals(classify.getIsTimely(),"1")){
                choose.add(product);
            }else {
                now.add(product);
            }
        }else {
            for (Long shoppingId : createOrdersDto.getShoppingIds()) {
                Shopping shopping = shoppingService.getById(shoppingId);
                Sku sku = skuService.getById(shopping.getSkuId());
                all = all.add(sku.getPrice().multiply(BigDecimal.valueOf(shopping.getNum())));
                Product product = productService.getById(sku.getProductId());
                if (StringUtils.equals(product.getNeedPay(),"1")){
                    needPay = "1";
                }
                if (sku.getStock() < shopping.getNum()){
                    throw new ServiceException(product.getName() + "库存不足");
                }
                Classify classify = classifyService.getById(product.getClassifyId());
                product.setSkus(new ArrayList(){{add(sku);}});
                if (StringUtils.equals(classify.getIsTimely(),"1")){
                    choose.add(product);
                }else {
                    now.add(product);
                }
            }
        }
        res.put("origin",all);
        if (createOrdersDto.getAccountCouponId() != null){
            AccountCoupon accountCoupon = accountCouponService.getById(createOrdersDto.getAccountCouponId());
            if (accountCoupon.getNeed().compareTo(all) > 0){
                return error("优惠券不满足最低金额");
            }
            res.put("derate",accountCoupon.getDerate());
            all = all.subtract(accountCoupon.getDerate());
            res.put("accountCouponId",createOrdersDto.getAccountCouponId());
        }else {
            List<AccountCoupon> accountCouponList = accountCouponService.lambdaQuery()
                    .eq(AccountCouponVo::getDelFlag, "0")
                    .eq(AccountCouponVo::getState, "0")
                    .le(AccountCouponVo::getNeed, all)
                    .eq(AccountCouponVo::getAccountId,getUserId())
                    .orderByDesc(AccountCouponVo::getDerate)
                    .list();
            if (accountCouponList.size() > 0){
                res.put("accountCouponId",accountCouponList.get(0).getAccountCouponId());
                res.put("derate",accountCouponList.get(0).getDerate());
                all = all.subtract(accountCouponList.get(0).getDerate());
            }
        }
        if (createOrdersDto.getStartAddressId() == null){
            AccountAddress accountAddress = accountAddressService.lambdaQuery()
                    .eq(AccountAddressVo::getAccountId, getUserId())
                    .eq(AccountAddressVo::getDelFlag, "0")
                    .eq(AccountAddressVo::getIsDefault, "1")
                    .one();
            res.put("address",accountAddress);
        }else {
            AccountAddress accountAddress = accountAddressService.getById(createOrdersDto.getStartAddressId());
            res.put("address",accountAddress);
        }
        res.put("otherTime",choose);
        res.put("inTime",now);
        res.put("all",all);
        res.put("needPay",needPay);
        return success(res);
    }

    /**
     * 获取商品
     */
    @PostMapping("/getProduct")
    @ApiOperation("获取商品")
    public AjaxResult getProduct(@RequestBody CreateOrdersDto createOrdersDto) {
        List<Product> res = new ArrayList<>();
        Map<String,List<Product>> map = new HashMap();
        map.put("inTime",new ArrayList<Product>());
        map.put("otherTime",new ArrayList<Product>());
        String key = "";
        if (createOrdersDto.getSkuId() != null){
            Product product = getProduct(createOrdersDto.getSkuId());
            product.setNum(createOrdersDto.getNum());
            Classify classify = classifyService.getById(product.getTopClassifyId());
            if (StringUtils.equals(classify.getIsTimely(),"1")){
                key = "otherTime";
            }else {
                key = "inTime";
            }
            List<Product> list = map.get(key);
            list.add(product);
            map.put(key,list);
//            res.add(product);
        }else {
            List<Long> shoppingIds = createOrdersDto.getShoppingIds();
            for (Long shoppingId : shoppingIds) {
                Shopping shopping = shoppingService.getById(shoppingId);
                Product product = getProduct(shopping.getSkuId());
                product.setNum(shopping.getNum());
                Classify classify = classifyService.getById(product.getTopClassifyId());
                if (StringUtils.equals(classify.getIsTimely(),"1")){
                    key = "otherTime";
                }else {
                    key = "inTime";
                }
                List<Product> list = map.get(key);
                list.add(product);
                map.put(key,list);
//                res.add(product);
            }
        }
        return success(map);
    }

    public Product getProduct(Long skuId){
        Sku sku = skuService.getById(skuId);
        Product product = productService.getById(sku.getProductId());
        List<Sku> skuList = new ArrayList<>();
        skuList.add(sku);
        product.setSkus(skuList);
        if (StringUtils.equals(product.getDelFlag(),"1") ||
                StringUtils.equals(product.getIsSale(),"0")
        ){
            throw new ServiceException(product.getName() + "已下架");
        }else if (StringUtils.equals(sku.getDelFlag(),"1")){
            throw new ServiceException(StringUtils.format("{}的{}已下架",product.getName(),sku.getFullName()));
        }
        return product;
    }

    public static com.aliyun.dysmsapi20170525.Client createClient(String key,String secret) throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(key)
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(secret);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public void sendCode(String phone,String code) throws Exception {
        com.aliyun.dysmsapi20170525.Client client = createClient("LTAI5t9qz3CiwfMLPKmd4DeH","LTAI5t9qz3CiwfMLPKmd4DeH");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",code);
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName("社区帮")
                .setTemplateCode("SMS_475900336")
                .setTemplateParam(jsonObject.toJSONString());
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse response = client.sendSmsWithOptions(sendSmsRequest, runtime);
            System.out.println(response.getStatusCode());
            System.out.println(response.getBody().getMessage());
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}
